let express = require("express");
let app = express();
let path = require('path')

app.use(express.urlencoded());
app.use(express.json());

//写处理跨域的中间件
app.use((request, response, next) => {
  //全部允许跨域
  // response.set('Access-Control-Allow-Origin','*')
  //允许单个跨域
  // response.set('Access-Control-Allow-Origin','http://127.0.0.1:5500')
  //允许几个跨域
  let arr = ["http://127.0.0.1:5500", "http://127.0.0.1:1010"];
  if (arr.includes(request.headers.origin)) {
    response.set("Access-Control-Allow-Origin", request.headers.origin);
    response.set("Access-Control-Allow-Headers", "*");
  }
  next();
});

//cors跨域
app.get("/userinfo", (request, response) => {
  let arr = ["http://127.0.0.1:5500", "http://127.0.0.1:1010"];
  if (arr.includes(request.headers.origin)) {
    response.set("Access-Control-Allow-Origin", request.headers.origin);
    response.send({
      code: 10000,
      msg: "查询成功",
      data: {
        name: "李博",
        age: 18,
        sex: "男",
      },
    });
  }
});

//jsonp跨域
app.get('/get',(request, response)=>{
    console.log(request.query);
    let {userid,cb} = request.query
    let data = {
        code: 10000,
        msg: "查询成功",
        data: {
          name: "李博",
          age: 18,
          sex: "男",
        },
      };
    response.send(`${cb}(${JSON.stringify(data)})`)
})

//查询信息的接口
app.get("/user", (request, response) => {
  let token = request.headers.token;
  console.log(token, "token");
  if (!token) {
    return response.send({
      code: 10002,
      msg: "无对应权限",
      data: null,
    });
  }

  let {userid} = request.query;

  //查询失败的情况
  if (userid !== "001") {
    return response.send({
      code: 10001,
      msg: "查询失败",
      data: null,
    });
  }

  //查询成功 响应
  response.send({
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男",
    },
  });

});

app.get("/1", (request, response) => {
  let filePath = path.resolve(__dirname, "./创建axios实例.html");
  response.sendFile(filePath);
});

app.get('/4',(request, response)=>{
  let filePath = path.resolve(__dirname,'./拦截器练习.html')
  response.sendFile(filePath)
})

app.listen(1010, () => {
  console.log("running");
});
